import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入store 模块
import store from '@/store/index.js'

// 导入需要的路由组件
// import Reg from '@/views/Reg/Reg.vue'
// 导入 Reg 组件
const Reg = () => import('@/views/Reg/Reg.vue')

// import Login from '@/views/Login/Login.vue'
const Login = () => import('@/views/Login/Login.vue')

// import Main from '@/views/Main/Main.vue'
const Main = () => import('@/views/Main/Main.vue')

// 导入子路由
// import Home from '@/views/Menus/Home/Home.vue'
const Home = () => import('@/views/Menus/Home/Home.vue')

// import UserInof from '@/views/Menus/User/UserInfo.vue'
const UserInof = () => import('@/views/Menus/User/UserInfo.vue')

// import UserAvatar from '@/views/Menus/User/UserAvatar.vue'
const UserAvatar = () => import('@/views/Menus/User/UserAvatar.vue')

// import UserPwd from '@/views/Menus/User/UserPwd.vue'
const UserPwd = () => import('@/views/Menus/User/UserPwd.vue')

// import ArtCate from '@/views/Menus/Article/ArtCate.vue'
const ArtCate = () => import('@/views/Menus/Article/ArtCate.vue')

// import ArtList from '@/views/Menus/Article/ArtList.vue'
const ArtList = () => import('@/views/Menus/Article/ArtList.vue')

Vue.use(VueRouter)

// src/router/index.js 路由模块

// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/',
    component: Main,
    redirect: '/home',
    children: [
      { path: 'home', component: Home },
      { path: 'user-info', component: UserInof },
      { path: 'user-avatar', component: UserAvatar },
      { path: 'user-pwd', component: UserPwd },
      { path: 'art-cate', component: ArtCate },
      { path: 'art-list', component: ArtList }
    ]
  },
  // 注册页面
  { path: '/reg', component: Reg },
  // 登录页面
  { path: '/login', component: Login }
]

const router = new VueRouter({
  routes
})
// 全局前置导航守卫
router.beforeEach((to, from, next) => {
  // 1.登录('/login')和注册页面不需要访问权限，直接放行
  // 2.除此之外，其他路由地址，都需要访问权限
  // 3.从 vuex 中获取token 的值，并判断是否有token
  // 3.1 如果有token ， 认为用户已经登陆了，直接放行
  // 3.2如果没有token ， 认为用户没有登陆，则强制跳转到登录页面
  if (to.path === '/login' || to.path === '/reg') {
    // 不需要权限
    next()
  } else {
    // 需要判断是否登录
    if (store.state.token) {
      // 有值，放行
      next()
    } else {
      next('/login')
    }
  }
})
export default router
